package com.zline.foodraise.ui.activity;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.ShippingAddrListAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.UserAddressBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.DrawableDividerItemDecoration;
import com.zline.foodraise.view.MyLinearLayoutManager;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by heshantao on 15/7/4.
 * 收货地址列表
 */
@EActivity(R.layout.activity_addr_list)
public class AddrListActivity extends ZlineActivity implements RecyclerItemClicked {
    private static final String LOG_TAG = AddrListActivity.class.getSimpleName();
    //标题
    @StringRes(R.string.shipping_addr)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.no_addr_rl)
    RelativeLayout no_addr_rl;
    @ViewById(R.id.shipping_addr_recyclerView)
    RecyclerView addr_recyclerView;
    //添加新收货地址按钮
    @ViewById(R.id.add_addr_rl)
    RelativeLayout add_addr_rl;
    SparseArray<UserAddressBean> addrArray;
    @Bean
    ShippingAddrListAdapter addrAdapter;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    LinearLayoutManager layoutManager;
    @Bean
    NetworkUtil networkUtil;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    //加载失败情况
    boolean loadFail = false;
    //移除地址的位置
    int deletPosition;

    @AfterViews
    void doSomeAfterViews() {
        addrArray = new SparseArray<UserAddressBean>();
        initView();
        requestData();
    }

    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            showLoadFailView(false);
            requestAddrList();
        } else {
            showLoadFailView(true);
        }
    }


    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
            add_addr_rl.setVisibility(View.GONE);
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
            add_addr_rl.setVisibility(View.VISIBLE);
        }
    }

    void initView() {
        title_tv.setText(title);
        initRecyclerView();
    }


    //初始化RecyclerView
    void initRecyclerView() {
        addr_recyclerView.setItemAnimator(new DefaultItemAnimator());
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        addr_recyclerView.setLayoutManager(layoutManager);
        addrAdapter.setAdapterData(addrArray);
        addrAdapter.setRecycleItemClickListener(this);
        addr_recyclerView.setAdapter(addrAdapter);
    }


    //请求收货地址列表
    void requestAddrList() {
        httpOperator.requestUserAddrList(httpUtil, requestAddrListHandler);
    }


    //获取收货地址回调
    AsyncHttpResponseHandler requestAddrListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAddrListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        addrArray = httpDataParsing.getUserAddrList(response);
                        loadMoreData(addrArray);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };


    //加载更多数据
    void loadMoreData(SparseArray<UserAddressBean> array) {
        addrAdapter.addAll(array);
        showNoAddr(array);

    }

    //请求移除地址
    void requestDelteAddr(int position) {
        UserAddressBean userAddressBean = addrArray.get(position);
        if (userAddressBean == null) return;
        long userAddrId = userAddressBean.getUserAddressId();
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requestRemoveAddr(httpUtil, userAddrId, requestRemoveAddrHandler);
        } else {
            TUtil.showShort(AddrListActivity.this, R.string.no_network);
        }

    }


    //移除地址回调
    AsyncHttpResponseHandler requestRemoveAddrHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestRemoveAddrHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        removeAddrListItem();
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    void removeAddrListItem() {
        addrAdapter.getArrys().remove(deletPosition);
        addrAdapter.notifyItemRemoved(deletPosition);
        showNoAddr(addrAdapter.getArrys());
    }


    //是否显示没有菜单的情况
    void showNoAddr(SparseArray<UserAddressBean> array) {
        if (array != null && array.size() == 0) {
            no_addr_rl.setVisibility(View.VISIBLE);
        } else {
            no_addr_rl.setVisibility(View.GONE);
        }
    }


    //添加。修改地址后的回调
    @OnActivityResult(Constant.ADDR_LIST_REQUEST_CODE)
    void onActivityResult(int resultCode) {
        switch (resultCode) {
            case Constant.ADD_MODIFY_ADDR_RESULT_CODE:
                addrAdapter.clear();
                requestData();
                break;
            default:
                break;
        }
    }


    @Click({R.id.add_addr_rl, R.id.app_common_header_left_icon_iv, R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_addr_rl:
                AddEditAddrActivity_.intent(AddrListActivity.this).flag(Constant.ADD_ADDR_FLAG)
                        .startForResult(Constant.ADDR_LIST_REQUEST_CODE);
                break;
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.reload_tv:
                requestData();
                break;
            default:
                break;
        }
    }


    @Override
    public void onRecyclerItemClicked(int position) {//修改地址信息
        UserAddressBean userAddressBean = addrArray.get(position);
        if (userAddressBean == null) return;
        AddEditAddrActivity_.intent(AddrListActivity.this)
                .flag(Constant.MODIFY_ADDR_FLAG)
                .userAddressBean(userAddressBean)
                .startForResult(Constant.ADDR_LIST_REQUEST_CODE);
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {


    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {
        deletPosition = position;
        requestDelteAddr(position);
    }
}
